import { sleep } from '.'

/**
 * 显示loading
 * @param mask - 是否显示遮罩
 * @param title - 提示文本
 */
export function showLoading(title = '加载中...', mask = true) {
  uni.showLoading({
    mask,
    title,
  })
}

export function showToast(options?: UniApp.ShowToastOptions) {
  const { icon = 'none', mask = false } = options || {}

  uni.showToast({
    icon,
    mask,
    ...options,
  })
}

/**
 * 隐藏loading
 */
export function hideLoading() {
  uni.hideLoading()
}

let hasModel = false
const modalPage = new Set<string>()
/**
 * 显示弹窗
 * !全局一次只展示一个弹窗，其他的往后排
 */
export async function showModal(options: UniApp.ShowModalOptions) {
  const page = getCurrentPages()
  const route = page[page.length - 1].route || ''
  if (modalPage.has(route)) {
    hasModel = true
  }
  else {
    hasModel = false
    modalPage.add(route)
  }
  console.log(modalPage)
  const { title = '提示', showCancel = true, complete } = options
  // while (hasModel)
  if (hasModel)
    await sleep(0.5)

  return new Promise((resolve, reject) => {
    hasModel = true
    uni.showModal({
      title,
      showCancel,
      success(res) {
        hasModel = false
        modalPage.delete(route)
        if (res.confirm)
          resolve(res)
        else if (res.cancel)
          reject(res)
      },
      fail(err) {
        hasModel = false
        modalPage.delete(route)
        reject(err)
      },
      ...options,
      complete: (res) => {
        hasModel = false
        modalPage.delete(route)
        // options?.complete?.(res);
        complete?.(res)
      },
    })
  })
}

/**
 * 显示错误弹窗 只有确定按钮
 * @param errMsg - 错误信息
 */
export function showErrorModal(errMsg: string) {
  return showModal({ content: errMsg, showCancel: false })
}
